import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '../ui/dropdown-menu'
import { LogOut, Loader } from 'lucide-react'
import { useState } from 'react'
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '../ui/dialog'
import { Button } from '../ui/button'
import { useCookieState, useRequest } from 'ahooks'
import { useNavigate } from 'react-router-dom'

interface AvatarDropdownProps {
  children: React.ReactNode
}

/**
 * 为侧边栏的头像添加的一个下拉菜单
 */
export default function AvatarDropdown(props: AvatarDropdownProps) {
  const navigate = useNavigate()

  const [, setAccessCode] = useCookieState('accessCode')
  const [, setNickname] = useCookieState('nickname')

  const [openLogoutDialog, setOpenLogoutDialog] = useState(false)

  const { run: handleLogout, loading: logoutLoading } = useRequest(
    async () => {
      setAccessCode(undefined)
      setNickname(undefined)
      if (window.CallBridge) {
        window.CallBridge.invokeMethod('Logout')
      } else {
        navigate('/login', { replace: true })
      }
    },
    { manual: true },
  )

  return (
    <Dialog open={openLogoutDialog} onOpenChange={setOpenLogoutDialog}>
      <DropdownMenu>
        <DropdownMenuTrigger className='focus:outline-none'>
          {props.children}
        </DropdownMenuTrigger>
        <DropdownMenuContent align='start'>
          <DropdownMenuItem
            className='p-2'
            onClick={() => setOpenLogoutDialog(true)}
          >
            <LogOut className='size-4 mr-2' />
            退出登录
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>提示</DialogTitle>
          <DialogDescription>确定要退出登录吗？</DialogDescription>
        </DialogHeader>
        <DialogFooter>
          <DialogClose asChild>
            <Button variant='outline' className='px-8'>
              取消
            </Button>
          </DialogClose>
          <Button
            className='px-8'
            disabled={logoutLoading}
            onClick={handleLogout}
          >
            {logoutLoading && <Loader className='size-4 mr-2 animate-spin' />}
            确定
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
